import axios from 'axios'
import { ElMessage } from 'element-plus'
import useUserStore from '@/stores/user'

const instance = axios.create({
  baseURL: '/ftyyptapi',
  timeout: 3000,
})

// 请求拦载器
instance.interceptors.request.use(
  (config) => {
    //todo
    const user = useUserStore()
    const token = user.userInfo.token

    if (token) {
      // config.headers.请求头 = token字符串
      // 方式1: config.headers.Authorization = `Bearer token字符串`
      // 方式2: config.headers.token = `token字符串`
      // 当前项目使用方式2传递token
      config.headers.token = token
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)
// 响应拦载器
instance.interceptors.response.use(
  (response) => {
    // 成功响应

    if (response.data.state === 401) {
      ElMessage.error(response.data.msg)
      return Promise.reject(response)
    } else {
      return response
    }
  },
  (error) => {
    // 失败响应  当响应状态码 status: 4xx 5xx
    return Promise.reject(error)
  },
)

export default instance
